﻿from flask import Flask, render_template, request, jsonify, json
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
from datetime import timedelta
from PIL import Image
import os

import classify
import manul
app = Flask(__name__)


# 设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


# 设置静态文件缓存过期时间
app.send_file_max_age_default = timedelta(seconds=1)
@app.route("/manual_classify", methods=['POST'])
def manual_classify():
    upload_file = request.files['uploadfile_ant']
    hint = request.form['hint']
    res = manul.manual_classify(hint)
    file_name = upload_file.filename
    basepath = os.path.dirname(__file__)
    dir_path = os.path.join(
        basepath, 'static/images', res, hint)
    upload_path = os.path.join(
        dir_path, secure_filename(upload_file.filename))
    os.makedirs(dir_path,exist_ok=True)
    if upload_file:
        upload_file.save(upload_path)
    return json.dumps({'result':f"(手动){res}"})


@app.route("/photo", methods=['POST'])
def photo():
    # 接收图片
    upload_file = request.files['uploadfile_ant']
    img = Image.open(upload_file.stream)
    '''# 获取图片名
    file_name = upload_file.filename
    # 获取图片路径
    basepath = os.path.dirname(__file__)
    # 一定要先创建该文件夹，不然会提示没有该路径
    upload_path = os.path.join(basepath, 'static/images', secure_filename(upload_file.filename))
    '''
    if upload_file:
        # upload_file.save(upload_path)
        res = classify.classify_by_content(img)
        if res == -1:
            return json.dumps({'result': 'classify api error'})
        else:
            return json.dumps({'result': res})
    else:
        return json.dumps({'result': 'unknown error'})


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=80)
